<template>
    <h1>{{ title }}</h1>
    <p>姓名children: {{ children.name }}</p>
    <p>年龄children: {{ children.age }}</p>
    <p>性别children: {{ children.sex }}</p>
    <p>信息children: {{ children.info }}</p>
    <p>信息children: {{ children.info?.a }}</p>
    <p>姓名person: {{ person.name }}</p>
    <p>年龄person: {{ person.age }}</p>
    <p>性别person: {{ person.sex }}</p>
    <p>count: {{ count }}</p>
    <p>arr: {{ obj.arr }}</p>
    <p>data.count: {{ state.data.count }}</p>
    <button @click="handleCount">count +1</button>
    <button @click="handleSex">显示sex</button>
    <button @click="changeWW">王五</button>
    <button @click="changeZL">赵六</button>
    <button @click="changeToRef">toRef</button>
    <button @click="changeValue">value</button>
    <button @click="changeValueA">valueA</button>
    <button @click="changeArr">arr</button>
    <button @click="changeCount">data</button>
</template>

<script setup lang="ts">
import com from "./com.vue";
import { useRoute } from "vue-router";
import { ref, reactive, toRefs, toRef, isRef, isReactive } from "vue";

const route = useRoute();

const title = ref("refReactive");

if (route.meta && route.meta.title) {
    title.value = route.meta.title as string;
}

const count = ref(0);

// 内部会将其 value 通过 reactive 包装成一个响应式对象

interface Person {
    name: string;
    age: number;
    info?: { a: string; c?: string }; // 可选属性
    sex?: string; // 可选属性
}

const children = ref<Person>({ name: "李四", age: 20, info: { a: "a" } });

const person: Person = reactive({
    name: "张三",
    age: 18,
});

// children.value 是一个 Proxy 对象
console.log(children.value);

console.log(isRef(children));
console.log(isReactive(children));

console.log(isRef(count));
console.log(isReactive(person));

const handleCount = () => {
    count.value++;
};

const handleSex = () => {
    children.value.sex = "男";
    person.sex = "女";
};

const changeWW = () => {
    // let { name, age } = person;
    // let { name: name1, age: age1 } = children.value;
    // name = "王五";
    // name1 = "王五";
};

const changeZL = () => {
    let { name, age } = toRefs(person);
    let { name: name1, age: age1 } = toRefs(children.value);
    name.value = "赵六";
    name1.value = "赵六";
};

const changeToRef = () => {
    let newPerson = toRef(person, "name");
    newPerson.value = "钱七";
};

const changeValue = () => {
    children.value.info = { a: "b", c: "c" };
};

const changeValueA = () => {
    children.value.info!.c = "d";
    children.value.info!.a = "d";
};

const obj = reactive({
    nested: { count: 0 },
    arr: ["foo", "bar"],
});

obj.arr = JSON.parse(JSON.stringify(obj.arr));

const changeArr = () => {
    obj.arr.push("baz");
};

const frozen = Object.freeze({ count: 0 });
const state = reactive({ data: frozen });

const changeCount = () => {
    // state.data.count++;
};
</script>

<style scoped></style>
